package edu.ynu.se.xiecheng.achitectureclass.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CameraTokenService {
    private final PropertyService propertyService;
    public CameraTokenService(PropertyService propertyService) {
        this.propertyService = propertyService;
    }

    @Value("${camera.token_url}")
    private String tokenUrl;

    @Value("${camera.account_id}")
    private String accountId;

    @Value("${camera.access_token}")
    private String accessToken;

    @Value("${camera.getTokenTime}")
    private String getTokenTime;

    private static final String TOKEN_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @EventListener(ApplicationReadyEvent.class)
    @Order(1)
    public String getAccessToken() {
        if (accessToken != null && !accessToken.isEmpty() && !isTokenExpired()) {
            return accessToken;
        }
        String Token = fetchNewToken();
        saveTokenToConfig(Token);
        return Token;
    }

    private String fetchNewToken() {
        String url = tokenUrl;
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求参数
        Map<String, String> params = new HashMap<>();
        params.put("accountId", accountId);

        // 创建请求体
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, String>> entity = new HttpEntity<>(params, headers);

        // 发送POST请求
        ResponseEntity<Map<String, Object>> response = restTemplate.exchange(url, HttpMethod.POST, entity, new ParameterizedTypeReference<>() {
        });

        // 解析token
        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null && responseBody.containsKey("data") && responseBody.get("data") instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                return  data.get("accessToken").toString();
            } else {
                throw new RuntimeException("Response body does not contain expected data.");
            }
        } else {
            throw new RuntimeException("Failed to fetch access token.");
        }
    }

    private boolean isTokenExpired() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(TOKEN_TIME_FORMAT);
            Date tokenDate = sdf.parse(getTokenTime);
            long diff = new Date().getTime() - tokenDate.getTime();
            return diff > 3600 * 1000; // Token有效期1小时
        } catch (Exception e) {
            return true;
        }
    }
    private void saveTokenToConfig(String Token) {
        // 保存token及获取时间到配置文件
        Map<String, String> properties = propertyService.getProperties();

        // 更新token和获取时间
        String currentTime = new SimpleDateFormat(TOKEN_TIME_FORMAT).format(new Date());
        properties.put("camera.access_token", Token);
        properties.put("camera.getTokenTime", currentTime);

        // 写回配置文件
        propertyService.writeProperties(properties);

        this.accessToken = Token;
        this.getTokenTime = currentTime;
    }
}

